//
//  CrazyInputBackView.m
//  webSocket
//
//  Created by 马军凯 on 2019/1/14.
//  Copyright © 2019年 ZH. All rights reserved.
//

#import "CrazyInputBackView.h"
#import "CrazyChatVoiceCenterView.h" //语音中间黑色的view
#import <AVFoundation/AVFoundation.h>
#import "lame.h" //转换

@interface CrazyInputBackView ()
{
    NSTimer *_timer; //定时器
    NSInteger _countDown; //倒计时
    
    AVAudioSession *_session;
    AVAudioRecorder *_recorder; //录音器
    AVAudioPlayer *_player; //音频播放器
    NSString *_recordFilePath; //录音文件沙盒地址
    NSString *_saveFilePath; //保存的路径
}

@property (nonatomic, strong) CrazyChatVoiceCenterView *voiceBackView;

@property (nonatomic, retain) NSMutableArray *addExtensionArray;

@end

@implementation CrazyInputBackView

+ (CrazyInputBackView *)sharedDefault {
    return [[self alloc] init];
}

- (instancetype)init {
    if (self = [super init]) {
        [self setData];
        self.backgroundColor = CRAZY_RGBR(242);
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:nil]];
        [self setLayoutView];
    }
    return self;
}

//View
- (void)setLayoutView {
    //总背景
    UIView *downAllBackView = [[UIView alloc] init];
    downAllBackView.frame = CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, 50);
    downAllBackView.backgroundColor = [UIColor clearColor];
    [self addSubview:downAllBackView];
    self.downAllBackView = downAllBackView;
    //切换语音和文本
    UIButton *changeVoiceAndTextBtn = [[UIButton alloc] init];
    changeVoiceAndTextBtn.frame = CGRectMake(10, 12.5, 25, 25);
    changeVoiceAndTextBtn.layer.masksToBounds = YES;
    changeVoiceAndTextBtn.layer.cornerRadius = changeVoiceAndTextBtn.frame.size.height / 2;
    [changeVoiceAndTextBtn setImage:[UIImage imageNamed:@"Crazy_chat_voice@2x.png"] forState:UIControlStateNormal];
    [changeVoiceAndTextBtn setImage:[UIImage imageNamed:@"Crazy_chat_text@2x.png"] forState:UIControlStateSelected];
    [self.downAllBackView addSubview:changeVoiceAndTextBtn];
    self.changeVoiceAndTextBtn = changeVoiceAndTextBtn;
    //输入框背景
    UIView *allWhiteBackView = [[UIView alloc] init];
    allWhiteBackView.frame = CGRectMake(45, 5, CRAZY_SCREEN_WIDTH - 90, 40);
    allWhiteBackView.backgroundColor = [UIColor whiteColor];
    allWhiteBackView.layer.masksToBounds = YES;
    allWhiteBackView.layer.cornerRadius = allWhiteBackView.frame.size.height / 2;
    [self.downAllBackView addSubview:allWhiteBackView];
    self.allWhiteBackView = allWhiteBackView;
    //+号
    UIButton *addExtensionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addExtensionBtn.frame = CGRectMake(CRAZY_SCREEN_WIDTH - 10 - 25, 12.5, 25, 25);
    addExtensionBtn.backgroundColor = [UIColor redColor];
    addExtensionBtn.layer.masksToBounds = YES;
    addExtensionBtn.layer.cornerRadius = addExtensionBtn.frame.size.height / 2;
    [addExtensionBtn setImage:[UIImage imageNamed:@"Crazy_chat_extension@2x.png"] forState:UIControlStateNormal];
    [addExtensionBtn setImage:[UIImage imageNamed:@"Crazy_chat_extension@2x.png"] forState:UIControlStateHighlighted];
    [self.downAllBackView addSubview:addExtensionBtn];
    self.addExtensionBtn = addExtensionBtn;
    //发送
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(CRAZY_SCREEN_WIDTH - 42.5, 10, 40, 30);
    sendBtn.backgroundColor = CRAZY_BACK_COLOR;
    sendBtn.layer.cornerRadius = 5;
    sendBtn.layer.masksToBounds = YES;
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:CRAZY_TEXT_COLOR forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    sendBtn.hidden = YES;
    [self.downAllBackView addSubview:sendBtn];
    self.sendBtn = sendBtn;
    
    //笑脸
    UIButton *smilingFacebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    smilingFacebtn.frame = CGRectMake(self.allWhiteBackView.width - 35, self.allWhiteBackView.height / 2 - 25 / 2, 25, 25);
    [smilingFacebtn setImage:[UIImage imageNamed:@"Crazy_chat_smilingFace@2x.png"] forState:UIControlStateNormal];
    [smilingFacebtn setImage:[UIImage imageNamed:@"Crazy_chat_smilingFace@2x.png"] forState:UIControlStateHighlighted];
    [self.allWhiteBackView addSubview:smilingFacebtn];
    self.smilingFacebtn = smilingFacebtn;
    //输入框
    UITextView *inputTextView = [[UITextView alloc] init];
    inputTextView.frame = CGRectMake(10, self.allWhiteBackView.height / 2 - 34 / 2, self.allWhiteBackView.width - 55, 34);
    inputTextView.returnKeyType = UIReturnKeySend;
    inputTextView.showsVerticalScrollIndicator = NO;
    inputTextView.showsHorizontalScrollIndicator = NO;
    inputTextView.backgroundColor = [UIColor whiteColor];
    inputTextView.enablesReturnKeyAutomatically = YES;
    inputTextView.font = [UIFont systemFontOfSize:15];
    [self.allWhiteBackView addSubview:inputTextView];
    self.inputTextView = inputTextView;
    //语音说话
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    voiceBtn.frame = self.allWhiteBackView.bounds;
    [voiceBtn setTitle:@"按住　说话" forState:UIControlStateNormal];
    [voiceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(clickVoiceDownBtn:) forControlEvents:UIControlEventTouchDown];
    [voiceBtn addTarget:self action:@selector(clickVoiceInSideBtn:) forControlEvents:UIControlEventTouchUpInside];
    [voiceBtn addTarget:self action:@selector(clickVoiceOutSideBtn:) forControlEvents:UIControlEventTouchUpOutside];
    [voiceBtn addTarget:self action:@selector(clickVoiceDragExitBtn:) forControlEvents:UIControlEventTouchDragExit];
    [voiceBtn addTarget:self action:@selector(clickVoiceDragEnterBtn:) forControlEvents:UIControlEventTouchDragEnter];
    [self.allWhiteBackView addSubview:voiceBtn];
    voiceBtn.hidden = YES;
    self.voiceBtn = voiceBtn;
    
    //+号扩展
    _extensionBackView = [CrazyChatAddExtensionBackView sharedDefault];
    _extensionBackView.frame = CGRectMake(0, 50, CRAZY_SCREEN_WIDTH, 240);
    _extensionBackView.hidden = YES;
    _extensionBackView.dataArray = self.addExtensionArray;
    [self addSubview:_extensionBackView];
    //表情扩展
    _expressionView = [[CrazyChatExpressionAllView alloc] initWithFrame:CGRectMake(0, 50, CRAZY_SCREEN_WIDTH, 240)];
    _expressionView.hidden = YES;
    [self addSubview:_expressionView];
}

//按住说话
- (void)clickVoiceDownBtn:(UIButton *)btn {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CrazyChatClosePlayVoice" object:nil];
    //判断是否开启权限
    if (![self canRecord]) {
        [UIAlertController alertViewWith:@"请启用麦克风-设置/隐私/麦克风"];
    }
    //修改文字
    [btn setTitle:@"松开　结束" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor grayColor];
    NSLog(@"说话啊啊啊奥术大师");
    //音量视图
    if (self.voiceBackView) {
        [self.voiceBackView removeFromSuperview];
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.voiceBackView = [[CrazyChatVoiceCenterView alloc] initWithFrame:CGRectMake(0, 0, 150, 170)];
    self.voiceBackView.center = window.center;
    [window addSubview:self.voiceBackView];
    //开始录音
    _countDown = 60;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(CrazyChatVolumeTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
    _session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [_session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if (_session == nil) {
        
    } else {
        [_session setActive:YES error:nil];
    }
    
    //获取文件沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    _recordFilePath = [path stringByAppendingString:@"/RRecord.wav"];
    _saveFilePath = [path stringByAppendingString:@"/RRecord.mp3"];
    //设置参数
    NSDictionary *recordParams = @{AVFormatIDKey : @(kAudioFormatLinearPCM),
                                   AVSampleRateKey : @44100.00f,
                                   AVNumberOfChannelsKey : @2,
                                   AVEncoderAudioQualityKey : @(AVAudioQualityMedium),
                                   AVLinearPCMBitDepthKey : @16,
                                   AVLinearPCMIsNonInterleaved : @NO,
                                   AVLinearPCMIsFloatKey : @NO,
                                   AVLinearPCMIsBigEndianKey : @NO};
    _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:_recordFilePath] settings:recordParams error:nil];
    if (_recorder) {
        _recorder.meteringEnabled = YES;
        [_recorder prepareToRecord];
        [_recorder record];
    }
}
//松开发送
- (void)clickVoiceInSideBtn:(UIButton *)btn {
    if (!_timer) { //松开之后为何还会触发
        return;
    }
    
    //停止录音 移除定时器
    [_timer invalidate];
    _timer = nil;
    
    if ([_recorder isRecording]) {
        [_recorder stop];
    }
    
    [self.voiceBackView removeFromSuperview];
    [btn setTitle:@"按住　说话" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    NSLog(@"发送录音啊");
    if (_countDown > 58) {
        [JKToast showWithText:@"说话时间太短"];
    } else {
        @try {
            int read, write;
            FILE *pcm = fopen([_recordFilePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
            fseek(pcm, 4 * 1024, SEEK_CUR); //skip file header
            FILE *mp3 = fopen([_saveFilePath cStringUsingEncoding:1], "wb");//output 输出生成的Mp3文件位置
            
            const int PCM_SIZE = 8192;
            const int MP3_SIZE = 8192;
            short int pcm_buffer[PCM_SIZE * 2];
            unsigned char mp3_buffer[MP3_SIZE];
            
            lame_t lame = lame_init();
            lame_set_in_samplerate(lame, 44100);
            lame_set_VBR(lame, vbr_default);
            lame_init_params(lame);
            
            do {
                read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
                if (read == 0) {
                    write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                } else {
                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                }
                fwrite(mp3_buffer, write, 1, mp3);
            } while (read != 0);
            
            lame_close(lame);
            fclose(mp3);
            fclose(pcm);
            
        } @catch (NSException *exception) {
            
        } @finally {
            CrazyWeakSelf;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"转换成功");
                [weakSelf uploadMp3];
            });
        }
    }
}
#pragma mark 上传MP3格式
- (void)uploadMp3 {
    NSData *fileData = [NSData dataWithContentsOfFile:_saveFilePath];
    NSString *urlString = [CRAZY_CHAT_API_DOMIN stringByAppendingString:@"customer/uploadFile"];
    NSDictionary *params = @{@"file" : fileData};
    [CrazyNetWork CrazyHttpFileUpload:urlString HUD:YES parameters:params imageArr:@[fileData] scale:0.5 nameArr:@[@"file"] fileNameArr:@[@"03030.mp3"] mimeType:@"video/mpeg" block:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@", dic[@"error"]] isEqualToString:@"0"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CrazyChatSendVoice" object:nil userInfo:@{@"voiceURL" : dic[@"ossUrl"], @"voiceTime": [NSString stringWithFormat:@"%ld", (60 - _countDown)]}];
        }
    } fail:^(NSError *error, NSString *url) {
        
    }];
}

//松开取消
- (void)clickVoiceOutSideBtn:(UIButton *)btn {
    //停止录音 移除定时器
    [_timer invalidate];
    _timer = nil;
    
    if ([_recorder isRecording]) {
        [_recorder stop];
    }
    
    [self.voiceBackView removeFromSuperview];
    [btn setTitle:@"按住　说话" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    NSLog(@"手势关闭啊");
}

//手势滑动出去了，这时改变音量图的内容
- (void)clickVoiceDragExitBtn:(UIButton *)btn {
    self.voiceBackView.volumeTextLabel.text = @"松开手指，取消发送";
    self.voiceBackView.volumeTextLabel.backgroundColor = [UIColor redColor];
    self.voiceBackView.cancelBackView.hidden = NO;
    self.voiceBackView.speakBackView.hidden = YES;
}

//手滑回来了
- (void)clickVoiceDragEnterBtn:(UIButton *)btn {
    self.voiceBackView.volumeTextLabel.text = @"手指上滑，取消发送";
    self.voiceBackView.volumeTextLabel.backgroundColor = [UIColor clearColor];
    self.voiceBackView.cancelBackView.hidden = YES;
    self.voiceBackView.speakBackView.hidden = NO;
}


//给+号内赋值
- (void)addExtensionContentWithArray:(NSArray *)array {
    [self.addExtensionArray addObjectsFromArray:array];
    
    _extensionBackView.dataArray = self.addExtensionArray;
}

#pragma mark 给+号扩展内容赋值
- (void)setData {
    NSArray *titleArray = @[@"相册", @"拍照", @"商品", @"订单"];
    NSArray *imageArray = @[@"Crazy_chat_photo@2x.png", @"Crazy_chat_camera@2x.png", @"CrazyChat_goods_list@2x.png", @"CrazyChat_order_list@2x.png"];
    for (int i = 0; i < titleArray.count; i++) {
        CrazyChatAddExtensionModel *model = [[CrazyChatAddExtensionModel alloc] init];
        model.image = imageArray[i];
        model.title = titleArray[i];
        [self.addExtensionArray addObject:model];
    }
}


#pragma mark 倒计时
- (void)CrazyChatVolumeTimer {
    [_recorder updateMeters];
    
    float level;
    float minDecibels = -80.0f;
    float decibeks = [_recorder averagePowerForChannel:0];
    NSLog(@"%f", decibeks);
    
    if (decibeks < minDecibels) {
        level = 0.0f;
    } else if (decibeks >= 0.0f) {
        level = 1.0f;
    } else {
        float root = 2.0f;
        float minAmp = powf(10.0f, 0.05f * minDecibels);
        float inverseAmpRange = 1.0f / (1.0f - minAmp);
        float amp = powf(10.0f, 0.05f * decibeks);
        float adjAmp = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    NSInteger voice = level * 10 + 1;
    voice = voice > 8 ? 8 : voice;
    NSLog(@"音量图：%ld", voice);
    [self.voiceBackView setVolumeLevelWithIndex:voice];
    
    _countDown --;
    //超时自动发送
    if (_countDown < 1) {
        [self clickVoiceInSideBtn:self.voiceBtn];
    }
}



#pragma mark 检查是否拥有麦克风权限
- (BOOL)canRecord {
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                bCanRecord = YES;
            } else {
                bCanRecord = NO;
            }
        }];
    }
    return bCanRecord;
}





#pragma mark 懒加载
- (NSMutableArray *)addExtensionArray {
    if (_addExtensionArray == nil) {
        _addExtensionArray = [NSMutableArray array];
        
    }
    return _addExtensionArray;
}


@end

















